#include <raylib.h>


static constexpr float width = 1200;
static constexpr float height = 800;
static constexpr float cell = 25;
static constexpr int cell_col = width / cell;
static constexpr int cell_row = height / cell;

static char state[2][cell_col + 2][cell_row + 2] = {0};
static int state_index = 0;

static bool running = false;

//
//  @brief 清楚状态
//
void clear_state() {
  state_index = 0;
  for (int i = 1; i <= cell_col; i++) {
    for (int j = 1; j <= cell_row; j++) {
      state[state_index][i][j] = 0;
    }
  }
}

//
//  @brief 更新细胞存活状态
//
void update_cell_states(bool force = false) {
  if (!force) {
    if (!running) return;  // 没有运行，直接返回
  }
  int last = state_index;
  state_index = last == 1 ? 0 : 1;

  for (int i = 1; i <= cell_col; i++) {
    for (int j = 1; j <= cell_row; j++) {
      int sum = state[last][i - 1][j - 1] + state[last][i - 1][j] +
                state[last][i - 1][j + 1] + state[last][i][j - 1] +
                state[last][i][j + 1] + state[last][i + 1][j - 1] +
                state[last][i + 1][j] + state[last][i + 1][j + 1];
      if (state[last][i][j]) {
        state[state_index][i][j] = (sum < 2 || sum > 3) ? 0 : 1;
      } else {
        state[state_index][i][j] = (sum == 3) ? 1 : 0;
      }
    }
  }
}

//
//  @brief 检测键盘事件
//
//
void detect_key_evt() {
  if (IsKeyPressed(KEY_ENTER)) {// 回车-运行
    running = true;
  }
  if (IsKeyPressed(KEY_R)) {// R - 复位
    running = false;
    clear_state();
  }
  if (IsKeyPressed(KEY_S)) { // S - 单步执行
    update_cell_states(true);
  }
	
}

//
//  @brief 检测鼠标是否在矩形上面(改变颜色)
//
void detect_mouse_evt() {
  if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
    if (!running) {
      Vector2 vec = GetMousePosition();
      int x = vec.x / cell;
      int y = vec.y / cell;
      state[state_index][x + 1][y + 1] =
          (state[state_index][x + 1][y + 1] == 1) ? 0 : 1;
    }
  }
}

int main(void) {
  InitWindow(width, height, "生命游戏");

  SetTargetFPS(10);

  while (!WindowShouldClose()) {
    detect_key_evt();    // 处理键盘
    detect_mouse_evt();  // 处理鼠标

    BeginDrawing();

    // ClearBackground(LIGHTGRAY);

    // 根据当前参数绘制矩形
    for (int i = 0; i < 60; i++) {
      for (int j = 0; j < 40; j++) {
        Color c = state[state_index][i + 1][j + 1] ? GREEN : GRAY;
        DrawRectangle(cell * i, cell * j, cell, cell, c);
        DrawRectangleLines(cell * i, cell * j, cell, cell, PURPLE);
      }
    }

    EndDrawing();

    update_cell_states();  // 更新细胞状态
  }

  CloseWindow();

  return 0;
}
